import * as TWEEN from '@tweenjs/tween.js';

interface ScrollArgs<T> {
  startData: T;
  endData: T;
  onUpdate: (value: T) => void;
  duration?: number;
}

/**
 * 滚动到指定位置
 * @param {ScrollArgs} 滚动参数
 */
export function scrollToEnd<T>(
  { startData, endData, onUpdate, duration }: ScrollArgs<T> = {
    startData: undefined as unknown as T,
    endData: undefined as unknown as T,
    onUpdate: () => {},
    duration: 200,
  },
) {
  let timeId: number;
  const tween = new TWEEN.Tween(startData as any)
    .to(endData as any, duration)
    .onUpdate((data) => {
      typeof onUpdate === 'function' && onUpdate(data as T);
    })
    .onComplete(() => {
      cancelAnimationFrame(timeId);
    })
    .start();

  // Setup the animation loop.
  function animate(time) {
    tween.update(time);
    timeId = requestAnimationFrame(animate);
  }
  timeId = requestAnimationFrame(animate);
  return tween;
}
